#!/usr/bin/env node
const fs = require('fs')
const Path = require('path')
const chalk = require('chalk')
const ErrorText = require('./errorText')

const projectPath = Path.join(__dirname, '../')
const modifiedFiles = process.argv.slice(2)
const configFilePath = Path.join(Path.resolve(process.argv[1], '../../../'), '.typorc.json')

let errorTextWarnings = []

const getConfigErrorText = () => {
  try {
    if (!fs.existsSync(configFilePath)) {
      return []
    }
    const fileString = fs.readFileSync(configFilePath).toString()
    return JSON.parse(fileString || '{}').errorTexts
  } catch (e) {
    return []
  }
}

const checkErrorText = (fileContentString, filePath) => {
  let warningTexts = []
  const configErrorTexts = getConfigErrorText()
  const errorTextArray = Array.from(new Set(ErrorText.errorTexts.concat(configErrorTexts)))
  errorTextArray.forEach((errorText) => {
    if(fileContentString.indexOf(errorText) > -1) {
      warningTexts.push(errorText)
    }
  })
  if(warningTexts.length !== 0) {
    errorTextWarnings.push({ file: filePath.replace(projectPath, ''), warningTexts })
  }
}

const listTextWarning = () => {
  if(errorTextWarnings.length === 0) {
    return
  }
  console.warn(chalk.yellow('\n** Warning! 请检查以下文件所含字符是否为错别字：\n'))
  errorTextWarnings.forEach((errorTextWarning) => {
    console.warn(chalk.green(`${errorTextWarning.file}: [ ${errorTextWarning.warningTexts.join(' | ')} ]\n`))
  })
}

const chceckFile = (filePath) => {
  if (!fs.existsSync(filePath)) {
    return
  }

  const fileContentString = fs.readFileSync(filePath).toString()
  checkErrorText(fileContentString, filePath)
}

for (let i = 0; i < modifiedFiles.length; i++) {
  chceckFile(modifiedFiles[i])
}

listTextWarning()
